package Example13_3;

import Test.StringToArithmetic;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;

public class Client {
    public static void main(String args[]) {
        //String [] mess ={"2010世界杯在哪举行?","巴西进入世界杯了码?","中国进入世界杯了码?"};
        Socket mysocket;
        DataInputStream in=null;
        DataOutputStream out=null;
        try{  mysocket=new Socket("127.0.0.1",2010);
            in=new DataInputStream(mysocket.getInputStream());
            out=new DataOutputStream(mysocket.getOutputStream());
            while (true){
                System.out.println("输入算式：");
                Scanner sc = new Scanner(System.in);
                String s = new String(sc.nextLine());
                s = StringToArithmetic.infixToSuffix(s);
                FileInputStream f=new FileInputStream("key1.dat");
                ObjectInputStream b=new ObjectInputStream(f);
                Key k=(Key)b.readObject( );
                Cipher cp=Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE, k);
                byte ptext[]=s.getBytes("UTF8");
                byte ctext[]=cp.doFinal(ptext);
                String cre = new String(ctext);
                System.out.println("密文为："+cre);
                String x=cre;
                MessageDigest m=MessageDigest.getInstance("MD5");
                m.update(x.getBytes("UTF8"));
                byte s0[ ]=m.digest( );
                String result="";
                for (int i=0; i<s0.length; i++){
                    result+=Integer.toHexString((0x000000ff & s0[i]) | 0xffffff00).substring(6);
                }
                System.out.println(result);
                out.writeUTF(ctext.length+"");
                for(int i=0;i<ctext.length;i++) {
                    out.writeUTF(ctext[i]+"");
                }
                out.writeUTF(result);
                String  ans=in.readUTF();   //in读取信息，堵塞状态
                System.out.println("客户收到服务器的回答:"+ans);
                Thread.sleep(500);
            }
        }
        catch(Exception e) {
            System.out.println("服务器已断开"+e);
        }
    }
}
